# -*-utf-8-*-

import os
import cv2
import time
import random
import filesystem

if __name__ == "__main__":
    # path = r'F:\work\dataset\video\leishan\2021\12\22\192.168.104.101\1640104200.mp4'
    cnt = 0  # 计数器

    rootDir = r'F:\work\dataset\video\leishan\2022\02'
    dirPath = filesystem.get_all_filepath(rootDir)
    for path in dirPath:
        cap = cv2.VideoCapture(path)

        if cap.isOpened() is not True:
            continue

        frameNumber = cap.get(7)
        # 获取一个随机帧号
        frameToStart = random.randint(1, frameNumber)

        print(frameToStart)
        # 要获取的帧号
        cap.set(cv2.CAP_PROP_POS_FRAMES, frameToStart)
        ret, frame = cap.read()
        if ret is not True:
            continue
        # cv2.imshow('images', frame)

        # 文件保存路径
        saveDir = r'E:\gec\picture'

        # [-5: -1]是2021，12...到文件名前的索引
        temSubName1 = path.split('\\')[-5: -1]
        subName1 = "_".join(temSubName1)

        # 原文件名
        subName2 = os.path.basename(path).split('.')[0]

        fileName = '{}_{}_frame_{}.jpg'.format(subName1, subName2, str(frameToStart))
        file = os.path.join(saveDir, fileName)
        cv2.imwrite(file, frame)

        cap.release()
        cv2.destroyAllWindows()

        cnt += 1

    print("截取完成，共截取{}张".format(cnt))